package com.example.demo.concurrent_shopping;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.Goods;
import com.example.demo.service.GoodsService;
import io.netty.handler.codec.string.StringDecoder;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.Codec;
import org.redisson.client.codec.StringCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import retrofit2.http.GET;

import java.util.Map;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.example.demo.concurrent_shopping;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2021/7/22 9:36]
 * @copyright: 2021 echovin.com
 */

@RestController
@RequestMapping("shopping")
public class ShoppingController {

    /*@Autowired
    private RedisTemplate redisTemplate;*/
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @GetMapping("show")
    public ResponseEntity<?> show(){
        //Map entries = redisTemplate.opsForHash().entries("GOODS_STOCK");
        RMap<Object, Object> goods_stock = redissonClient.getMap("GOODS_STOCK", new StringCodec());
        return ResponseEntity.ok(goods_stock);
    }

    @GetMapping("shop/{goodsId}/{num}")
    public ResponseEntity<?> shoppingPage(@PathVariable Long goodsId, @PathVariable Long num){
        if (goodsId ==null || goodsId <= 0L){
            return ResponseEntity.ok("商品数据不存在");
        }

        if (num ==null || num <=0L){
            return ResponseEntity.ok("购买商品数量应大于0");
        }

        RLock lock = redissonClient.getLock(goodsId.toString());
        try {
            lock.lock();
            RMap<Object, Object> goods_stock = redissonClient.getMap("GOODS_STOCK", new StringCodec());
            String goodsStock = (String)goods_stock.get(goodsId.toString());
            if (null == goodsStock){
                return ResponseEntity.ok("商品数据不存在");
            }
            Goods goods = JSONObject.parseObject(goodsStock, Goods.class);
            if (goods.getStock().intValue() - num.intValue() <= 0){
                return ResponseEntity.ok("购买商品："+goods.getName()+"库存不足无法购买");
            }
        } finally {
            lock.unlock();
        }
        return null;

    }
}
